import mongoose, { Document, Schema } from 'mongoose'
import dayjs from 'dayjs'
import { Counter } from './counter'

export interface IFile extends Document {
  id: number
  original_name: string
  file_name: string
  file_path: string
  file_size: number
  mime_type: string
  created_at: string
  updated_at: string
  created_by: number | null
  updated_by: number | null
}

const FileSchema: Schema = new Schema({
  id: {
    type: Number,
    unique: true,
    description: '文件id'
  },
  original_name: {
    type: String,
    required: true,
    description: '原始文件名'
  },
  file_name: {
    type: String,
    required: true,
    description: '存储文件名'
  },
  file_path: {
    type: String,
    required: true,
    description: '文件存储路径'
  },
  file_size: {
    type: Number,
    required: true,
    description: '文件大小(字节)'
  },
  mime_type: {
    type: String,
    required: true,
    description: 'MIME类型'
  },
  created_at: {
    type: String,
    default: () => dayjs().format('YYYY-MM-DD HH:mm:ss'),
    description: '创建时间'
  },
  updated_at: {
    type: String,
    default: () => dayjs().format('YYYY-MM-DD HH:mm:ss'),
    description: '最后更新时间'
  },
  created_by: {
    type: Number,
    default: null,
    description: '创建者id'
  },
  updated_by: {
    type: Number,
    default: null,
    description: '最后更新者id'
  }
})

// 保存前处理
FileSchema.pre<IFile>('save', async function (next) {
  if (this.isNew) {
    try {
      const counter = await Counter.findByIdAndUpdate(
        { _id: 'file_id' },
        { $inc: { seq: 1 } },
        { new: true, upsert: true }
      )
      this.id = counter.seq
      next()
    } catch (error: any) {
      next(error)
    }
  } else {
    next()
  }
})

// 更新时更新时间戳
FileSchema.pre<IFile>('findOneAndUpdate', function (next) {
  this.set({ updated_at: dayjs().format('YYYY-MM-DD HH:mm:ss') })
  next()
})

// 配置 toJSON 输出
FileSchema.set('toJSON', {
  transform: function (doc, ret) {
    const { _id, __v, ...rest } = ret
    return rest
  }
})

export const File = mongoose.model<IFile>('file', FileSchema, 'file')
